package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * @author spt
 * @description
 **/
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "登录接口")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
       User user = userService.findByUsername(param.getUsername());
//        //创建固定盐
//        String salt = "abc";
//        //讲密码和盐拼接加密
//        String passwordSalt = param.getPassword()+salt;
//        //用户不存在或密码不匹配则登录失败
//        String password = DigestUtils.md5DigestAsHex(passwordSalt.getBytes());
//        //从数据库查出加盐md5哈希值
        String saltPassword = userService.findmd5Password(user.getUsername());
//        if (password.equalsIgnoreCase(saltPassword)) {
//            //模拟用户登录成功
//            log.info("[登录]成功，user:{}",user.getUsername());
//            return new Result(true, MessageConst.LOGIN_SUCCESS);
//        }
//        log.info("[登录]失败，user:{}",param.getUsername());

//BCrypt加盐加密算法
                //随机生成一个盐值
                //String gensalt = BCrypt.gensalt(10);
                //使用生成的盐值加密密码
                //String hashpw = BCrypt.hashpw(a, gensalt);
                    //System.out.println(hashpw);
                //判断当前密码是否正确
        boolean checkpw = BCrypt.checkpw(param.password, saltPassword);
                if (checkpw){
                    log.info("[登录]成功，user:{}",user.getUsername());
                     return new Result(true, MessageConst.LOGIN_SUCCESS);
                }
        log.info("[登录]失败，user:{}",param.getUsername());
        return new Result(false, MessageConst.LOGIN_FAIL);

    }
}
